<template>
  <div class="form">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="120px" label-position="right">
        <el-form-item label="Name">
          <el-input v-model="searchForm.supername" placeholder="Name">
          </el-input>
        </el-form-item>
        <el-form-item label="Contract" prop="contract">
          <el-date-picker v-model="searchForm.contract" type="datetimerange" range-separator="-"
            start-placeholder="Select Start Date" end-placeholder="Select End Date" format="MM-dd-yyyy"
            value-format="MM-dd-yyyy">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="find()" plain>Search</el-button>
          <el-button type="primary" v-permission="['skus.store']" plain @click="add">+Add Supplier</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="supername" label="Supplier Name" width="220" align="center" />
        <el-table-column prop="attention_name" label="Attention Name" width="140" align="center" />
        <el-table-column prop="supertel" label="Tel" width="100" />
        <el-table-column prop="superaddress" label="Address" width="200" />
        <el-table-column label="Contract Date" width="200" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.cstartdate }}~{{ scope.row.cenddate }}</span>
          </template>
        </el-table-column>

        <el-table-column label="Price" align="center">
          <template v-slot="scope">
            <span>{{scope.row.price}} </span>
          </template>
        </el-table-column>
        <el-table-column label="Supplier SKU" align="center">
          <template v-slot="scope">
            <span>{{scope.row.csku}} </span>
          </template>
        </el-table-column>


        <el-table-column label="Created Time" width="220">
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="200">
          <template slot-scope="scope">
            <el-button plain v-permission="['skus.edit']" @click="edit(scope.row.id)">edit</el-button>
            <el-button type="danger" plain v-permission="['skus.destroy']" @click="del(scope.row.id)">delete</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>
    <UploadSku :show.sync="isShow" :module="module" :id="cid" />

    <div class="form">
      <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
        customClass="customWidth">
        <el-form v-if="dialogFormVisible" ref="ruleForm" :model="formData" :rules="rules" label-width="160px"
          style="width:85%">

          <el-form-item label="Supplier" prop="Supplier">
            <el-select v-model="formData.supper_id" placeholder="Choose Supplier" style="width:300px">
              <el-option v-for="item in suppliers" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="Product Uom" style="width: 460px;">
            <span>{{formDatainfo.uom}}{{formDatainfo.uom_sku}}</span>
          </el-form-item>

          <el-form-item label="Price" prop="price" style="width: 460px;">
            <el-input v-model="formData.price" placeholder="Enter Price"></el-input>
          </el-form-item>

          <el-form-item label="Supplier SKU" prop="csku" style="width: 460px;">
            <el-input v-model="formData.csku" placeholder="Enter Supplier SKU"></el-input>
          </el-form-item>

          <el-form-item label="Supplier UOM" prop="cskuom" style="width: 460px;">
            <el-input v-model="formData.cskuom" placeholder="Enter Supplier UOM"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="save('ruleForm')">Submit</el-button>
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
        </div>
      </el-dialog>
    </div>


  </div>
</template>
<script>
  import CURD from "@/mixin/CURD";
  import {
    index as skulist,
    update as skupdate
  } from "@/api/suppersku";
  import {
    index as superindex
  } from "@/api/supplier";
  import {
    show as proshow
  } from "@/api/product";
  import UploadSku from "@/components/UploadSku";
  export default {
    name: "supplierIndex",
    components: {
      UploadSku
    },
    props: {
      id: {
        type: String,
        default: 0
      }
    },
    mixins: [CURD],
    data() {
      return {
        status: [{
          id: null,
          name: "all",
        }, {
          id: "added",
          name: "added",
        }, {
          id: "notadded",
          name: "not added",
        }],
        tableData: [],
        page: {
          total: null,
          per_page: 10,
          sizes: [10, 20, 25, 50],
          current_page: 1
        },
        cid: this.id,
        isEdit: false,
        isNew: false,
        formData: {},
        module: "suppersku",
        newTitle: "New supplier",
        editTitle: "Edit supplier",
        isPaginate: true,
        searchForm: {},
        imageUrl: "",
        dialogFormPasswordVisible: false,
        isUploadFile: false,
        importDialogVisible: false,
        fileReader: new FileReader(),
        isShow: false,
        suppliers: [],
        formDatainfo: ""
      };
    },
    async created() {
      const {
        data
      } = await superindex(1, 100); // 假设index是一个异步函数
      console.log(data, "ssss")
      this.suppliers = data;
      this.searchForm.product_id = this.cid;
      await this.fetchData();
      this.id = this.$route.query.id
      if (this.id > 0) {
        const {
          data
        } = await proshow(this.id);
        this.formDatainfo = data;
      }
    },
    methods: {
      uploadData() {
        this.isShow = true;
      },
      saveData() {
        this.save("ruleForm");
      },
      handleUpdates(row, index, ac) {
        const id = row.id
        var fd = {
          csku: row.inputvalue,
          id: row.id,
          action: ac
        }
        skupdate(fd).then(res => {
          this.$message.success(res.info)
          this.tableData[index].csku = row.inputvalue
        });
      },
      async fetchData() {
        this.searchForm.customer_id = this.cid;
        const res = await skulist(
          this.page.current_page,
          this.page.per_page,
          this.searchForm
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data.map(item => {
            item.inputvalue = ""
            return item
          })
        } else {
          this.tableData = res.data.map(item => {
            item.inputvalue = ""
            return item
          });
        }
        let {
          rules
        } = require(`@/model/${this.module}`);
        this.rules = rules;
        if (res.meta) {
          // 分页
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      async add() {
        let {
          Model
        } = require(`@/model/${this.module}`);
        this.formData = new Model();
        this.isNew = true;
        this.isEdit = false;
        this.setTitle();
        this.formData.cskuom = this.formDatainfo.uom
        this.dialogFormVisible = true;
      },
      setTitle() {
        this.title = this.isNew === true ? this.newTitle : this.editTitle;
        this.cmdTitle = this.isNew === true ? "save" : "modify";
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.product_id = this.cid;
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success(info);
              }
              if (this.isNew) {

                this.formData.title = this.formDatainfo.name;
                this.formData.sku = this.formDatainfo.sku;

                let {
                  store
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await store(this.formData);
                this.$message.success(info);
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      parseErrors(errors) {
        let info = "";
        let name = errors.name;
        if (Array.isArray(name)) {
          name.forEach((item) => {
            info += item + ",";
          });
        }
        info = info.substring(0, str.length - 1);
        return info;
      },
      async edit(id) {
        let {
          show
        } = require(`@/api/${this.module}`);
        let {
          data
        } = await show(id);
        this.formData = data;
        this.isNew = false;
        this.isEdit = true;
        this.setTitle();
        this.dialogFormVisible = true;
      },
      async del(id) {
        try {
          await this.$confirm("This operation will permanently delete data. Do you want to continue?", "prompt", {
            confirmButtonText: "determine",
            cancelButtonText: "cancel",
            type: "warning"
          });
          let {
            destroy
          } = require(`@/api/${this.module}`);
          let {
            info
          } = await destroy(id);
          this.$message.success(info);
          await this.fetchData();
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled deletion"
          });
        }
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      }
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>